import { SelectedPage } from "../../shared/types";
import AnchorLink from "react-anchor-link-smooth-scroll";
import { useNavigate, useLocation } from "react-router-dom";

type Props={
  page: string; // 明确指定page为string类型
  selectedPage:SelectedPage;
  setSelectedPage:(value:SelectedPage)=>void;
}

const Link=({
  page,
  selectedPage,
  setSelectedPage
}:Props)=>{
  const navigate = useNavigate();
  const location = useLocation();
  const lowerCasePage = page.toLowerCase().replace(/\s/g,"") as SelectedPage;
  
  // 将中文菜单映射到路由或首页 section 的 id
  const routeMap: { [key: string]: { type: 'route' | 'anchor', path: string, anchorId?: string } } = {
    "首页": { type: 'route', path: '/', anchorId: 'home' },
    "器材申请": { type: 'route', path: '/equipment', anchorId: 'equipment' },
    "场地管理": { type: 'route', path: '/venues', anchorId: 'venue' },
    "赛事申请": { type: 'route', path: '/events', anchorId: 'eventManage' },
    "罚款条例": { type: 'route', path: '/penalty-rules' },
    "公告中心": { type: 'route', path: '/announcements' },
    "登录": { type: 'route', path: '/login' },
    "注册": { type: 'route', path: '/register' },
    "用户管理": { type: 'route', path: '/user-management' },
    "修改密码": { type: 'route', path: '/change-password' }
  };

  const mapping = routeMap[page];
  
  const handleClick = () => {
    setSelectedPage(lowerCasePage);
    
    // 如果当前在首页且有对应的锚点ID，使用锚点链接
    if (location.pathname === '/' && mapping?.anchorId) {
      const element = document.getElementById(mapping.anchorId);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
        return;
      }
    }
    
    // 否则使用路由导航
    if (mapping && mapping.type === 'route') {
      navigate(mapping.path);
    }
  };
  
  // 如果当前在首页且有锚点ID，使用AnchorLink
  if (location.pathname === '/' && mapping?.anchorId) {
    return (
      <AnchorLink
        className={`${selectedPage === lowerCasePage ? "text-primary-500" : ""} hover:text-primary-300 transition duration-500`}
        offset="70"
        href={`#${mapping.anchorId}`}
        onClick={() => setSelectedPage(lowerCasePage)}
      >
        {page}
      </AnchorLink>
    );
  }
  
  // 否则使用普通按钮进行路由导航
  return (
    <button
      className={`${selectedPage === lowerCasePage ? "text-primary-500" : ""} hover:text-primary-300 transition duration-500 text-left`}
      onClick={handleClick}
    >
      {page}
    </button>
  );
}

export default Link;